<?php
require_once(dirname(__FILE__)."/config.php");
CheckPurview('sys_MakeHtml');
require_once(DEDEROOT."/data/cache/inc_catalog_base.inc");
require_once(DEDEINC."/channelunit.func.php");
require_once(DEDEINC."/customfields.func.php");
require_once(DEDEADMIN."/inc/inc_archives_functions.php");
$pubdate = $sortrank = time();
$sortup = 0;
$color = '';
$sortrank = AddDay($pubdate,$sortup);
$senddate = time();
$adminid = $cuserLogin->getUserID();
$flag = isset($flags) ? join(',',$flags) : '';
//$ismake = $ishtml == 0 ? -1 : 0;
$writer =  cn_substrR($writer,20);
$source = cn_substrR($source,30);
$filename = trim(cn_substrR($filename,40));
$sqlChannelid = $dsql->GetOne(" Select channeltype From  `#@__arctype` where id='$typeid' ");
$channelid = $sqlChannelid['channeltype'];
$result = $dsql->GetOne(" Select nid,fieldset,listfields From  `#@__channeltype` where id='$channelid' ");

function PrintAutoFieldsAdd2(&$fieldset,$loadtype='all')
{
	$dtp = new DedeTagParse();
	$dtp->SetNameSpace('field','<','>');
	$dtp->LoadSource($fieldset);
	$dede_addonfields = '';
	if(is_array($dtp->CTags))
	{
		foreach($dtp->CTags as $tid=>$ctag)
		{
			if($ctag->GetName()=='bigpic') continue;
                        if($ctag->GetName()=='body') continue;
			if($loadtype!='autofield'
			|| ($loadtype=='autofield' && $ctag->GetAtt('autofield')==1) )
			{
				$dede_addonfields .= ( $dede_addonfields=="" ? $ctag->GetName().",".$ctag->GetAtt('type') : ";".$ctag->GetName().",".$ctag->GetAtt('type') );
				echo  GetFormItemA($ctag);
			}
		}
	}
	echo "<input type='hidden' name='dede_addonfields' value=\"".$dede_addonfields."\">\r\n";
}

if($_GET[action]=='getChannelID'){
    if($_GET[type]=='1'){
        if($result[nid]=='article'){
            echo '0';
        }elseif($result[nid]=='product'){
            echo PrintAutoFieldsAdd2($result[fieldset]);
        }
    }elseif($_GET[type]=='2'){
        $array = explode(',', $result[listfields]);
        echo json_encode($array);
    }
    
    exit;
}

$useip = GetIP();
$litpic = $cfg_clihost.$_GET[path].'files/'.time().'_'.$_GET[rank].'.'.$_GET[format];
$keywords =  substr($_GET[name], 0,-4);
$description =  substr($_GET[name], 0,-4);
$redirecturl = '';
if(!isset($autokey)) $autokey = 0;
	if(!isset($remote)) $remote = 0;
	if(!isset($dellink)) $dellink = 0;
	if(!isset($autolitpic)) $autolitpic = 0;

//分析处理附加表数据
	$inadd_f = '';
	$inadd_v = '';
	if(!empty($dede_addonfields))
	{
		$addonfields = explode(';',$dede_addonfields);
		$inadd_f = '';
		$inadd_v = '';
		if(is_array($addonfields))
		{
			foreach($addonfields as $v)
			{
				if($v=='')
				{
					continue;
				}
				$vs = explode(',',$v);
				if($vs[1]=='htmltext'||$vs[1]=='textdata') //HTML文本特殊处理
				{
					${$vs[0]} = AnalyseHtmlBody(${$vs[0]},$description,$litpic,$keywords,$vs[1]);
				}
				else
				{
					if(!isset(${$vs[0]}))
					{
						${$vs[0]} = '';
					}
					${$vs[0]} = GetFieldValueA(${$vs[0]},$vs[1],$arcID);
				}
				$inadd_f .= ','.$vs[0];
				$inadd_v .= " ,'".${$vs[0]}."' ";
			}
		}
	}
        

        
if(empty($typeid))
	{
		ShowMsg("请指定文档的栏目！","-1");
		exit();
	}
        
if(!TestPurview('a_Check,a_AccCheck,a_MyCheck'))
	{
		$arcrank = -1;
	}
	//生成文档ID
	$arcID = GetIndexKey($arcrank,$typeid,$sortrank,$channelid,$senddate,$adminid);
	if(empty($arcID))
	{
		ShowMsg("无法获得主键，因此无法进行后续操作！","-1");
		exit();
	}
//	if(trim($title) == substr($name, 0,-4))
//	{
//		ShowMsg('标题不能为空', '-1');
//		exit();
//	}
        
function returnFileList(){
    $dir = '..'.$_GET[path];
    if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if(pathinfo($file, PATHINFO_EXTENSION)==$_GET[format] or pathinfo($file, PATHINFO_EXTENSION)==strtoupper($_GET[format])){
                $filenamearray[] = iconv( 'gb2312','utf-8', $file);
            }
            
        }
        closedir($dh);
    }
}
natsort  ($filenamearray);
//$json = json_encode(iconv( 'gb2312', 'UTF-8',$filenamearray));
//return iconv( 'gb2312', 'UTF-8' , json_encode($filenamearray));

//return urlencode(iconv("gb2312","utf-8",json_encode($filenamearray)));
return json_encode($filenamearray);
}

if($_GET[action]=='achieve'){
    echo returnFileList();
}
if($_GET[action]=='upload'){
    $dir = '..'.$_GET[path];
//    echo $_GET[name].'上传成功';
    if(!is_dir($dir.'files')){
        mkdir($dir.'files');
    }
    $filename=$dir.iconv('utf-8', 'gb2312', $_GET[name]);;
    $newfile = $dir.'files/'.time().'_'.$_GET[rank].'.'.$_GET[format];
    $sqlNewFile = $cfg_clihost.$_GET[path].'files/'.time().'_'.$_GET[rank].'.'.$_GET[format];
    if (!copy($filename, $newfile)) {
        echo "failed to copy $file...\n";
    }else{
//        echo $typeid;
//        echo $arcID.'\n';
        $pathname = explode('/', $_GET[path]);
//        print_r($pathname);
        array_pop($pathname);
//        echo $pathname[count($pathname)-1];
        $pathname = $pathname[count($pathname)-1].'_'.$rank;
        $r_n=$articleName==1?$pathname:substr($_GET[name], 0,-4);
        $query = "INSERT INTO `#@__archives`(id,typeid,sortrank,flag,ismake,channel,arcrank,click,title,writer,source,
	litpic,pubdate,senddate,mid,description,keywords,filename)
    VALUES ('$arcID','$typeid','$sortrank','$flag','$ishtml','$channelid','$arcrank','0',
    '".  $r_n."','$writer','$source','$sqlNewFile','$pubdate','$senddate',
    '$adminid','".  substr($_GET[name], 0,-4)."','".  substr($_GET[name], 0,-4)."','');";
        
        
        
        
        if(!$dsql->ExecuteNoneQuery($query))
	{
		$gerr = $dsql->GetError();
		$dsql->ExecuteNoneQuery("Delete From `#@__arctiny` where id='$arcID'");
		ShowMsg("把数据保存到数据库主表 `#@__archives` 时出错，请把相关信息提交给DedeEIMS官方。".str_replace('"','',$gerr),"javascript:;");
		exit();
	}else{
            //保存到附加表
            $cts = $dsql->GetOne("Select addtable From `#@__channeltype` where id='$channelid' ");
            $addtable = trim($cts['addtable']);
            if(!empty($addtable))
            {
                    $useip = GetIP();
                    $r_b=$copyInContent==1?'<img src="'.$sqlNewFile.'"/>':substr($_GET[name], 0,-4);
                    if($result[nid]=='article'){
                        $query = "INSERT INTO `{$addtable}`(aid,typeid,userip,body{$inadd_f}) Values('$arcID','$typeid','$useip','". $r_b."'{$inadd_v})";
                    }elseif($result[nid]=='product'){
                        $query = "INSERT INTO `{$addtable}`(aid,typeid,userip,bigpic,body{$inadd_f}) Values('$arcID','$typeid','$useip','". $sqlNewFile."','". $r_b."'{$inadd_v})";
                    }
                    
                    if(!$dsql->ExecuteNoneQuery($query))
                    {
                            $gerr = $dsql->GetError();
                            $dsql->ExecuteNoneQuery("Delete From `#@__archives` where id='$arcID'");
                            $dsql->ExecuteNoneQuery("Delete From `#@__arctiny` where id='$arcID'");
                            ShowMsg("把数据保存到数据库附加表 `{$addtable}` 时出错，请把相关信息提交给DedeEIMS官方。".str_replace('"','',$gerr),"javascript:;");
                            exit();
                    }
                    //生成HTML
//                    echo $arcID;
                    $artUrl = MakeArt($arcID,true,true);
                    if($artUrl=='')
                    {
                            $artUrl = $cfg_phpurl."/view.php?aid=$arcID";
                    }
            }
            echo $filename.'上传成功';
        }
        
    }

    
    //echo 'cool';
}
?>